package frontend.admin;

import backend.DuplicatedItem;
import backend.GeneralDatabase;
import service.DatabaseManager;

import javax.swing.*;
import java.awt.*;

public class AddUserDialog extends JDialog {
    static GeneralDatabase db=null;
    public interface AddUserCallback {
        void onUserAdded(String username, String password,int level);
    }

    public AddUserDialog(JFrame owner, AddUserCallback callback) {
        super(owner, "添加用户", true);
        setSize(400, 280);
        setLocationRelativeTo(owner);
        setLayout(new BorderLayout(10, 10));

        // 表单面板
        JPanel formPanel = new JPanel(new GridLayout(3, 2, 10, 10));
        formPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 10, 15));

        JTextField userField = new JTextField();
        JPasswordField passField = new JPasswordField();
        JTextField roleField = new JTextField();
        JTextField levelField = new JTextField();

        formPanel.add(new JLabel("账号："));
        formPanel.add(userField);
        formPanel.add(new JLabel("密码："));
        formPanel.add(passField);
        formPanel.add(new JLabel("等级："));
        formPanel.add(levelField);

        add(formPanel, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 10));
        JButton saveBtn = new JButton("保存");
        JButton cancelBtn = new JButton("取消");

        saveBtn.setBackground(new Color(70, 130, 180));
        saveBtn.setForeground(Color.WHITE);
        saveBtn.setFocusPainted(false);

        saveBtn.addActionListener(e -> {
            String user = userField.getText().trim();
            String pass = new String(passField.getPassword()).trim();
            String levelStr = levelField.getText().trim();

            if (!user.isEmpty() && !pass.isEmpty() && !levelStr.isEmpty()) {
                try {
                     db = DatabaseManager.getInstance();

                    int permLevel = Integer.parseInt(levelStr);
                    db.tryUseradd("admin", user, pass, permLevel);
                    callback.onUserAdded(user, pass, permLevel);
                    dispose();
                } catch (NumberFormatException ex) {
                    JOptionPane.showMessageDialog(this, "等级必须为数字");
                } catch (DuplicatedItem ex) {
                    JOptionPane.showMessageDialog(this, "用户名已存在");
                } catch (Exception ex) {
                    JOptionPane.showMessageDialog(this, "添加失败: " + ex.getMessage());
                }
            } else {
                JOptionPane.showMessageDialog(this, "请填写所有字段");
            }
        });

        cancelBtn.addActionListener(e -> dispose());

        buttonPanel.add(saveBtn);
        buttonPanel.add(cancelBtn);
        add(buttonPanel, BorderLayout.SOUTH);
    }
}
